package com.redoor.app.stake.common.utils;

/**
 * Created by wangjunlei on 2018/3/20.
 */

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * xss非法标签过滤工具类
 * 过滤html中的xss字符
 * @author xbz
 */
public class JsoupUtil {

    /**
     * 使用自带的basicWithImages 白名单
     * 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
     * strike,strong,sub,sup,u,ul,img
     * 以及a标签的href,img标签的src,align,alt,height,width,title属性
     */
    private static final Whitelist whitelist = Whitelist.none();
    /** 配置过滤化参数,不对代码进行格式化 */
    private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
    static {
        // 富文本编辑时一些样式是使用style来进行实现的
        // 比如红色字体 style="color:red;"
        // 所以需要给所有标签添加style属性
        whitelist.addAttributes(":all", "style");
    }

    public static String clean(String content) {
        if(!StringUtils.isEmpty(content)){
            content = content.trim();
        }
        content = clearXss(content);
        return Jsoup.clean(content, "", whitelist, outputSettings);
    }

    public static String clearXss(String value){
        if (value == null || "".equals(value)) {
            return value;
        }
        value = value.replaceAll("<", "＜").replaceAll(">", "＞");
        value = value.replaceAll("\\(", "(").replace("\\)", ")");
        value = value.replaceAll("'", "’");
        value = value.replaceAll("&", "＆");
        value = value.replaceAll("#", "＃");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        return value;
    }


    public static void main(String[] args) throws
            IOException {
        String text = "  \\<a>11  ";
        System.out.println(clean(text));
    }
}